package com.niiwoo.civet.user.service.local;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 登录账号相关 redis 操作
 *
 * key = project:module:key:scope
 */
public interface LoginAccountRedisService {

    String KEY_PREFIX = "civet-user:";

    // 验证码
    String SMS_CODE_FORMAT = KEY_PREFIX + "sms:code:%s:%s";

    // 验证码当天发送次数
    String SMS_CODE_DAY_TIMES_FORMAT = KEY_PREFIX + "sms:dayTimes:%s:%s";

    // 验证码当月发送次数
    String SMS_CODE_MONTH_TIMES_FORMAT = KEY_PREFIX + "sms:monthTimes:%s:%s";

    // 密码错误次数
    String LOGIN_PASSWORD_ERROR_TIMES_FORMAT = KEY_PREFIX + "loginAccount:passwordErrorTimes:%s";

    // 肖像认证错误次数
    String PORTRAIT_AUTH_ERROR_TIMES_FORMAT = KEY_PREFIX + "loginAccount:portraitAuthErrorTimes:%s";

    /**
     * 查询
     */
    default Optional<String> getCacheValue(String format, Object[] params) {
        return Optional.ofNullable(StringUtils.isBlank(format) ? null : getStringRedisTemplate().opsForValue().get(formatCacheKey(format, params)));
    }

    /**
     * key格式化
     */
    default String formatCacheKey(String format, Object... params) {
        return params != null && params.length > 0 ? String.format(format, params) : format;
    }

    /**
     * 赋值
     */

    default void setCacheValue(String format, Object[] params, String value, long timeout, TimeUnit timeUnit) {
        if (StringUtils.isBlank(format) || StringUtils.isBlank(value)) {
            return;
        }
        getStringRedisTemplate().opsForValue().set(formatCacheKey(format, params), value, timeout, timeUnit);
    }

    /**
     * 删除
     */
    default void delCacheValue(String format, Object[] params) {
        if (StringUtils.isBlank(format)) {
            return;
        }
        getStringRedisTemplate().delete(formatCacheKey(format, params));
    }

    /**
     * 递增
     */
    default Optional<Long> incrCacheValue(String format, Object[] params, long timeout, TimeUnit timeUnit) {
        if (StringUtils.isBlank(format)) {
            return Optional.empty();
        }
        String key = formatCacheKey(format, params);
        long count = getStringRedisTemplate().opsForValue().increment(key, 1L);
        getStringRedisTemplate().expire(key, timeout, timeUnit);
        return Optional.of(count);
    }

    /**
     * 设置过期
     */
    default void expireCacheValue(String format, Object[] params, long timeout, TimeUnit timeUnit) {
        getStringRedisTemplate().expire(formatCacheKey(format, params), timeout, timeUnit);
    }


    RedisTemplate<String, String> getStringRedisTemplate();

}
